package com.wzl.myviewgroup.keypad;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.wzl.myviewgroup.R;
import com.wzl.myviewgroup.utils.SizeUtils;

public class KeypadView extends ViewGroup {

    private static final String TAG = "KeypadView";

    private static final int DEFAULT_MARGIN = SizeUtils.dip2px(2);
    public static final int DEFAULT_ROW=4;
    public static final int DEFAULT_COLUMN=3;
    private int mRow = DEFAULT_ROW;
    private int mColumn = DEFAULT_COLUMN;

    private int mTextColor;
    private float mTextSize;
    private int mItemPressBgColor;
    private int mItemNormalBgColor;
    private int mItemMargin;
    private OnKeyClickListener monKeyClickListener;


    public KeypadView(Context context) {
        this(context, null);
    }

    public KeypadView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public KeypadView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        initAttrs(context, attrs);

        setupItems();


    }

    //创建子view，设置属性，添加到ViewGroup中
    private void setupItems() {
        //先清空原来的内容
        removeAllViews();
        //创建子view
        for (int i = 0; i < 11; i++) {
            TextView item = new TextView(getContext());
            //内容
            if(i == 10) {
                item.setTag(true);
                item.setText("del");
            }else {
                item.setTag(false);
                item.setText(String.valueOf(i));
            }
            //大小,单位默认px
            if (mTextSize!=-1) {
                item.setTextSize(TypedValue.COMPLEX_UNIT_PX,mTextSize);
            }

            //剧中
            item.setGravity(Gravity.CENTER);
            //字体颜色
            item.setTextColor(mTextColor);

            //设置点击背景，使用代码实现，不使用xml
            //GradientDrawable:
            //  设置背景颜色,设置圆角,设置边框,设置边框颜色,边框宽度,边框宽度单位
            item.setBackground(providerItemBg());

            //设置点击事件
            item.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d(TAG, "onClick: ");
                    if (monKeyClickListener != null && v instanceof TextView) {
                        String s = ((TextView) v).getText().toString();
                        if ((boolean)v.getTag()) {
                            monKeyClickListener.onDeleteClick(s);
                        }else {
                            monKeyClickListener.onNumberClick(Integer.parseInt(s));
                        }
                    }
                }
            });
            addView(item);
        }

    }
    private Drawable providerItemBg(){//
        //按下bg
        GradientDrawable pressDrawable = new GradientDrawable();
        //设备背景颜色
//        pressDrawable.setColor(getResources().getColor(R.color.key_item_press_color));
        pressDrawable.setColor(mItemPressBgColor);
        //  设置圆角
        pressDrawable.setCornerRadius(SizeUtils.dip2px(5));
        //StateListDrawable 状态列表,按下状态，普通状态,
        StateListDrawable bg =new StateListDrawable();//
        //按下状态的bg
        bg.addState(new int[]{android.R.attr.state_pressed},pressDrawable);
        //普通状态的bg
        GradientDrawable normalDrawable =new GradientDrawable();
//        normalDrawable.setColor(getResources().getColor(R.color.key_item_color));
        normalDrawable.setColor(mItemNormalBgColor);
        normalDrawable.setCornerRadius(SizeUtils.dip2px(5));
        bg.addState(new int[]{},normalDrawable);
        return bg;

    }

    private void initAttrs(Context context, AttributeSet attrs) {
        // 获取自定义属性
        // TypedArray
        //   getIndexCount() 获取属性个数
        //   getIndex(int at) 获取属性索引
        //   getResources() 获取资源
        //   getText(int index) 获取文本
        //   getString(int index) 获取文本
        //   getNonResourceString(int index) 获取文本
        //   getBoolean(int index, boolean defValue) 获取布尔值
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.KeypadView);
        //获取属性值
        //numberColor
        mTextColor = a.getColor(R.styleable.KeypadView_numberColor, context.getResources().getColor(R.color.white));
        Log.d(TAG, "initAttrs: mTextColor = " + mTextColor);
        //numberTextSize 单位:px
        mTextSize = a.getDimensionPixelSize(R.styleable.KeypadView_numberSize, -1);
        Log.d(TAG, "initAttrs: mTextSize = " + mTextSize);
        //itemMargin
        mItemMargin = a.getDimensionPixelSize(R.styleable.KeypadView_itemMargin, DEFAULT_MARGIN);
        Log.d(TAG, "initAttrs: mItemMargin = " + mItemMargin);
        //itemPressColor
        mItemPressBgColor = a.getColor(R.styleable.KeypadView_itemPressColor, context.getResources().getColor(R.color.key_item_press_color));
        //itemNormalColor
        mItemNormalBgColor = a.getColor(R.styleable.KeypadView_itemNormalColor, context.getResources().getColor(R.color.key_item_color));
        a.recycle();
    }

    //测量
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int horizontalPadding = getPaddingLeft()+getPaddingRight();
        int verticalPadding = getPaddingTop()+getPaddingBottom();

        //测量子view
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        Log.d(TAG, "onMeasure: widthSize = " + widthSize);
        Log.d(TAG, "onMeasure: heightSize = " + heightSize);
        //—行三列，求出列宽，三等分
        int perItemwidth =(widthSize -(mColumn+1)*mItemMargin-horizontalPadding)/mColumn;
        int perItemHeight =(heightSize -(mRow+1)*mItemMargin-verticalPadding)/mRow;
        int normalwidthspec =MeasureSpec.makeMeasureSpec(perItemwidth,MeasureSpec.EXACTLY);
        int deletewidthSpec =MeasureSpec.makeMeasureSpec(perItemwidth *2+mItemMargin,MeasureSpec.EXACTLY);
        int heightspec =MeasureSpec.makeMeasureSpec(perItemHeight,MeasureSpec.EXACTLY);
        for(int i=0;i<getChildCount();i++){
            View item =getChildAt(i);
            boolean isDelete =(boolean)item.getTag();
            //测量子view,
            // measureChild(child,childWidthSpace,childHeightSpace);
            item.measure(isDelete ?deletewidthSpec :normalwidthspec,heightspec);
        }

        //测量自己
        setMeasuredDimension(widthMeasureSpec,heightMeasureSpec);

    }

    //布局
    //布局,布局孩子
    //l,t,r,b
    //l:左上角x坐标
    //t:左上角y坐标
    //r:右下角x坐标
    //b:右下角y坐标
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int childCount =getChildCount();

        int paddingTop =getPaddingTop();
        int paddingLeft = getPaddingLeft();

        int left =mItemMargin,top,right,bottom;

        for(int i=0;i<childCount;i++){
            //求出当前元素在第几行，第几列
            int rowIndex =i/mColumn; //从0开始
            int columnindex =i%mColumn;
            if(columnindex ==0){
                left =mItemMargin+paddingLeft;
            }
            View item =getChildAt(i);
            top =rowIndex *item.getMeasuredHeight()+mItemMargin*(rowIndex+1)+paddingTop;
            right =left +item.getMeasuredWidth();
            bottom =top +item.getMeasuredHeight();
            //布局
            item.layout(left,top,right,bottom);
            left +=item.getMeasuredWidth()+mItemMargin;
        }

    }

    public interface OnKeyClickListener{
        void onNumberClick(int  number);
        void onDeleteClick(String delete);
    }
    public void setOnKeyClickListener(OnKeyClickListener listener){
        monKeyClickListener = listener;
    }

    public int getmTextColor() {
        return mTextColor;
    }

    public void setmTextColor(int mTextColor) {
        this.mTextColor = mTextColor;
    }

    public float getmTextSize() {
        return mTextSize;
    }

    public void setmTextSize(float mTextSize) {
        this.mTextSize = mTextSize;
    }

    public int getmItemPressBgColor() {
        return mItemPressBgColor;
    }

    public void setmItemPressBgColor(int mItemPressBgColor) {
        this.mItemPressBgColor = mItemPressBgColor;
    }

    public int getmItemNormalBgColor() {
        return mItemNormalBgColor;
    }

    public void setmItemNormalBgColor(int mItemNormalBgColor) {
        this.mItemNormalBgColor = mItemNormalBgColor;
    }

    public int getmItemMargin() {
        return mItemMargin;
    }

    public void setmItemMargin(int mItemMargin) {
        this.mItemMargin = mItemMargin;
    }
}
